package com.lishuang.DAO.DeviceDAO;

import com.lishuang.DAO.SqlConnector;
import com.lishuang.domain.json.Device;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @author LiShuang
 * @version 1.0.0
 * @date 2022/11/12 17:31
 */
public class deviceDAOImp implements deviceDAO {

    private SqlConnector sql;
    private PreparedStatement statement;
    public deviceDAOImp(SqlConnector sql){this.sql=sql;}

    //插入
    @Override
    public boolean Insert(Device device) throws Exception {
        String query = "INSERT INTO `device` (`id`, `name`,`propertytype`,`uuid`,`status`,`priority`) VALUES (?,?,?,?,?,?)";
        statement=sql.getConnection().prepareStatement(query);
        statement.setInt(1,device.getDeviceId());
        statement.setString(2,device.getDeviceName());
        statement.setString(3,device.getDeviceCategory());
        statement.setString(4,device.getUuid());
        statement.setString(5,device.getDeviceStatus().toString());
        statement.setInt(6,device.getDevicePriority());
        int update = statement.executeUpdate();
        if(update>0){
            return true;
        }
        else{
            return false;
        }
    }

    //列出所有
    @Override
    public List<Device> findAll() throws Exception {
        String query = "SELECT * FROM device";
        statement=sql.getConnection().prepareStatement(query);
        ResultSet result = statement.executeQuery();
        Device device;
        List<Device> list = new ArrayList<Device>();
        while (result.next()){
            int deviceId = result.getInt(1);
            String category = result.getString(2);
            device = new Device(deviceId,category);
            list.add(device);
        }
        return list;
    }

    //按值查找
    @Override
    public Device findByIdx(int deviceId) throws Exception {
        String query = "SELECT * FROM device WHERE `id`=?";
        statement = sql.getConnection().prepareStatement(query);
        statement.setInt(1,deviceId);
        ResultSet rs = statement.executeQuery();
        Device device = null;
        if(rs.next()){
            String content = rs.getString(2);
            device=new Device(deviceId,content);
        }
        return device;
    }
}

